package com.zzxz.practicaltrainingsys.controller;


import com.github.pagehelper.PageInfo;
import com.zzxz.practicaltrainingsys.entity.Log;
import com.zzxz.practicaltrainingsys.service.LogService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/log")
@CrossOrigin
public class LogController {

    @Autowired
    private LogService logService;

    @PostMapping("/insert")
    public int insertLog(@RequestBody Log log, HttpServletRequest request) {
        // 获取客户端IP地址
        String ip = request.getRemoteAddr();
        log.setIpAddress(ip);

        // 获取用户代理信息
        String userAgent = request.getHeader("User-Agent");
        // 解析操作系统和浏览器信息
        String os = parseOperatingSystem(userAgent);
        String browser = parseBrowser(userAgent);

        log.setOS(os);
        log.setIE(browser);
        log.setCreateDate(LocalDateTime.now());

        return logService.insertLog(log);
    }

    // 解析操作系统信息
    private String parseOperatingSystem(String userAgent) {
        if (userAgent == null) return "未知";

        if (userAgent.contains("Windows")) {
            return "Windows";
        } else if (userAgent.contains("Mac")) {
            return "Mac OS";
        } else if (userAgent.contains("Linux")) {
            return "Linux";
        } else if (userAgent.contains("Android")) {
            return "Android";
        } else if (userAgent.contains("iOS")) {
            return "iOS";
        } else {
            return "未知";
        }
    }

    // 解析浏览器信息
    private String parseBrowser(String userAgent) {
        if (userAgent == null) return "未知";

        if (userAgent.contains("Chrome")) {
            return "Chrome";
        } else if (userAgent.contains("Firefox")) {
            return "Firefox";
        } else if (userAgent.contains("Safari")) {
            return "Safari";
        } else if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            return "IE";
        } else if (userAgent.contains("Edge")) {
            return "Edge";
        } else {
            return "未知";
        }
    }

    @GetMapping("/list")
    public List<Log> getLogList() {
        return logService.getLogList();
    }

    @ApiOperation("查找登录日志信息（分页查询）")
    @GetMapping("/pages")
    public PageInfo<Log> getLogByPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        return logService.getLogByPage(pageNum, pageSize);
    }

}
